import 'package:azlistview/azlistview.dart';

import 'city_bean.dart';
import 'json_data.dart';

class SelectCityModel {
  List<CityBean> dataList = [];

  void initData() async {
    List<CityBean> originList = cityData.map((e) {
      CityBean city = CityBean.fromJson(e);
      if (city.pinyin?.isNotEmpty ?? false) {
        String tag = city.pinyin!.substring(0, 1).toUpperCase();
        if (RegExp("[A-Z]").hasMatch(tag)) {
          city.tagIndex = tag;
        } else {
          city.tagIndex = "#";
        }
      } else {
        city.tagIndex = "#";
      }
      return city;
    }).toList();
    _handleList(originList);
  }

  void _handleList(List<CityBean> list) {
    dataList.clear();
    dataList.addAll(list);
    // A-Z sort.
    sortListBySuspensionTag(dataList);
    // show sus tag.
    setShowSuspensionStatus(dataList);

    List<String> hot =
        hotCityData.map<String>((e) => e['cityName'] ?? '').toList();

    CityBean hotCity = CityBean(
      cityName: "热门城市",
      tagIndex: "↑",
      children: hot,
    );
    dataList.insert(0, hotCity);
  }

  /// sort list by suspension tag.
  /// 根据[A-Z]排序。
  static void sortListBySuspensionTag(List<ISuspensionBean>? list) {
    if (list == null || list.isEmpty) return;
    list.sort((a, b) {
      if (a.getSuspensionTag() == "@" || b.getSuspensionTag() == "#") {
        return -1;
      } else if (a.getSuspensionTag() == "#" || b.getSuspensionTag() == "@") {
        return 1;
      } else {
        return a.getSuspensionTag().compareTo(b.getSuspensionTag());
      }
    });
  }

  /// set show suspension status.
  /// 设置显示悬停Header状态。
  static void setShowSuspensionStatus(List<ISuspensionBean>? list) {
    if (list == null || list.isEmpty) return;
    String? tempTag;
    for (int i = 0, length = list.length; i < length; i++) {
      String tag = list[i].getSuspensionTag();
      if (tempTag != tag) {
        tempTag = tag;
        list[i].isShowSuspension = true;
      } else {
        list[i].isShowSuspension = false;
      }
    }
  }
}
